package com.addplus.townmall.server.web.consumer.action;


import com.addplus.townmall.server.api.constant.ErrorCode;
import com.addplus.townmall.server.api.model.base.ReturnDataSet;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.addplus.townmall.server.web.consumer.container.AddplusContainer;
import com.addplus.townmall.server.web.consumer.utils.WebUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

@Controller
public class ServiceAction {

    @Autowired
    private AddplusContainer addplusContainer;

    /**
     * get请求，下载试题模板
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/get/web/download/questionModule/QuestionService/insertQuestionTemplate")
    public void insertQuestionTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ZipInputStream zip=null;
        OutputStream bos = null;
        //将文件进行打包下载
        try {
            String downloadName = "sasdfds.zip";
            File file=new File(downloadName);
            zip = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
            bos = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
            byte[] byArr = new byte[1024 * 1024];
            int bytesRead;
            while ((bytesRead = zip.read(byArr)) != -1) {
                bos.write(byArr, 0, bytesRead);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bos.close();
            zip.close();
        }
    }
    /**
     * get请求 根据ids导出试题
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/get/web/download/questionModule/QuestionService/exportQuestionByIds")
    public ReturnDataSet exportQuestionByIds(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReturnDataSet returnDataSet=null;
        try {
            returnDataSet = addplusContainer.invoke(
                    "web." +
                            "questionModule." +
                            "QuestionService",
                    "exportQuestionByIds",
                    request.getParameterMap(),
                    true
            );
            response.setContentType("application/msword");
            File file = createDoc((Map<String, Object>) returnDataSet.getDataSet());
            String fileName = (String) ((Map<String, Object>) returnDataSet.getDataSet()).get("paperName") + ".docx";

            InputStream bis = null;
            OutputStream bos = null;

            try {
                long fileLength = file.length();
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/msword");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
                bis = new FileInputStream(file);
                bos = response.getOutputStream();
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (file != null) {
                    file.delete(); // 删除临时文件
                }
            }
        }catch (Exception e){
            return returnDataSet;
        }
        return returnDataSet;
    }

    /**
     * post请求 导出试卷
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/post/web/download/paperModule/PaperService/exportPaper")
    public ReturnDataSet exportPaper(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream is;
        String contentStr;
        Map param = new HashMap();
        ReturnDataSet returnDataSet=null;
        try
        {
            is = request.getInputStream();
            contentStr = WebUtil.inputStreamString(is);
            param = addplusContainer.stringToMap("web"+"."+"paperModule"+"."+"PaperService","exportPaper",contentStr,false);
        }
        catch (Exception e)
        {
            returnDataSet = new ReturnDataSet();
            returnDataSet.setReturnCode(ErrorCode.SYS_ERROR_SERVICE.getCode());
            returnDataSet.setErrorInfo(e.getMessage());
            return returnDataSet;
        }
        returnDataSet=addplusContainer.invoke("web"+"."+"paperModule"+"."+"PaperService","exportPaper",param,false);
        File file = createDoc((Map<String, Object>) returnDataSet.getDataSet());
        String fileName=(String)((Map<String, Object>) returnDataSet.getDataSet()).get("paperName")+".docx";

        InputStream bis = null;
        OutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new FileInputStream(file);
            bos = response.getOutputStream();
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if(file != null) {
                file.delete(); // 删除临时文件
            }
        }
        return returnDataSet;
    }


    @RequestMapping(value = "/post/web/download/paperModule/PaperService/autoExportPaper")
    public ReturnDataSet autoExportPaper(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream is;
        String contentStr;
        Map param = new HashMap();
        ReturnDataSet returnDataSet=null;
        try
        {
            is = request.getInputStream();
            contentStr = WebUtil.inputStreamString(is);
            param = addplusContainer.stringToMap("web"+"."+"paperModule"+"."+"PaperService","autoExportPaper",contentStr,false);
        }
        catch (Exception e)
        {
            returnDataSet = new ReturnDataSet();
            returnDataSet.setReturnCode(ErrorCode.SYS_ERROR_SERVICE.getCode());
            returnDataSet.setErrorInfo(e.getMessage());
            return returnDataSet;
        }
        returnDataSet=addplusContainer.invoke("web"+"."+"paperModule"+"."+"PaperService","autoExportPaper",param,false);
        File file = createDocAuto((Map<String, Object>) returnDataSet.getDataSet());
        String fileName=(String)((Map<String, Object>) returnDataSet.getDataSet()).get("paperName")+".docx";

        InputStream bis = null;
        OutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new FileInputStream(file);
            bos = response.getOutputStream();
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if(file != null) {
                file.delete(); // 删除临时文件
            }
        }
        return returnDataSet;
    }

    private File createDocAuto(Map<String,Object> dataMap){
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
        Template t = null;

        String name = (String)dataMap.get("paperName")+".docx";
        File file = new File(name);
        try {
            t = configuration.getTemplate("autoExam.ftl");

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return file;
    }

    private File createDoc(Map<String,Object> dataMap){
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
        Template t = null;

        String name = (String)dataMap.get("paperName")+".docx";
        File file = new File(name);
        try {
            t = configuration.getTemplate("exam.ftl");

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return file;
    }
//    @RequestMapping(value = "/get/web/download/townordermodule/TownOrderDownService/exportOrder")
//    public ReturnDataSet exportOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        ReturnDataSet returnDataSet = addplusContainer.invoke(
//                "web." +
//                        "townordermodule." +
//                        "TownOrderDownService",
//                "exportOrder",
//                request.getParameterMap(),
//                true
//        );
//        if (returnDataSet.getReturnCode().equals(ErrorCode.SYS_SUCCESS.getCode())) {
//            String fileName = "订单导出" + LocalDateTime.now().toString();
//            ExportUtil.responseSetProperties(fileName, response);
//            try (final OutputStream os = response.getOutputStream()) {
//                List<Map<String, Object>> list = (List<Map<String, Object>>) returnDataSet.getDataSet();
//                ExportUtil.responseSetProperties(fileName, response);
//                ExportUtil.doExport(list, "订单号,订单状态,订单类型,下单用户,会员备注,下单店铺,收货人名称,收货人电话,收货人地址,付款时间,付款端口,发票类型,商品类型,发票抬头类型,发票抬头,发票内容,发票金额,税号,发票备注说明,注册地址,注册电话,收票人邮箱,商品名称,单价,数量,实付金额,商品id,下单活动,商品自定义编码,一级分类,二级分类,规格,物流公司,快递单号", "orderNumber,orderStatus,orderType,memberName,memberRemark,storeName,receiptName,receiptMobile,receiptFullAddress,payDate,payTypeName,invoiceType,type,invoiceTitleType,invoiceTitle,invoiceContext,invoiceAmount,invoiceCode,invoiceRemark,buyerAddressAndPhone,buyerBankNameAndAccount,recipientEmail,shopName,shopPrice,purchaseQuantity,realTotalPrice,shopProductId,shopActiveType,shopCustomizeCode,firstCategory,secondCategory,shopSpecificationSkuJson,shopCourierName,shipOrderNumber", os);
//                returnDataSet.setDataSet(true);
//            } catch (Exception e) {
//                returnDataSet.setErrorCode(ErrorCode.SYS_ERROR_NULLDATE);
//            }
//        }
//        return returnDataSet;
//    }

//    @RequestMapping(value = "/get/web/download/giftcardmodule/GiftCardDownService/exportGiftBatchCard")
//    public ReturnDataSet exportMember(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        ReturnDataSet returnDataSet = addplusContainer.invoke(
//                "web." +
//                        "giftcardmodule." +
//                        "GiftCardDownService",
//                "exportGiftBatchCard",
//                request.getParameterMap(),
//                true
//        );
//        if (returnDataSet.getReturnCode().equals(ErrorCode.SYS_SUCCESS.getCode())) {
//            String fileName = "礼品卡导出" + LocalDateTime.now().toString();
//            ExportUtil.responseSetProperties(fileName, response);
//            try (final OutputStream os = response.getOutputStream()) {
//                List<Map<String, Object>> list = (List<Map<String, Object>>) returnDataSet.getDataSet();
//                ExportUtil.responseSetProperties(fileName, response);
//                ExportUtil.doExport(list, "ID,账号,密码,面值,是否有效期,有效期开始日期,有效期结束日期,状态,批次,创建时间", "id,giftAccount,giftPassword,giftValue,isDeadline,startDate,endDate,giftStatus,giftBatch,gmtCreate", os);
//                returnDataSet.setDataSet(true);
//            } catch (Exception e) {
//                returnDataSet.setErrorCode(ErrorCode.SYS_ERROR_NULLDATE);
//            }
//        }
//        return returnDataSet;
//    }
}